import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { authMiddleware } from '../middleware/auth';
import { ApiResponse } from '../utils/response';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 获取用户余额
router.get('/', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    let balance = await prisma.userBalance.findUnique({
      where: { userId }
    });

    // 如果没有余额记录，创建一个初始记录
    if (!balance) {
      balance = await prisma.userBalance.create({
        data: {
          userId,
          balance: 0,
          frozen: 0,
          total: 0
        }
      });
    }

    res.json(ApiResponse.success(balance, '잔액 조회에 성공했습니다.'));
  } catch (error) {
    console.error('잔액 조회 오류:', error);
    res.status(500).json(ApiResponse.error('잔액 조회에 실패했습니다.'));
  }
});

// 获取余额变动历史（可选功能，暂时简单实现）
router.get('/history', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;
    const { page = 1, limit = 20 } = req.query;

    // 获取充值和提现记录作为余额变动历史
    const deposits = await prisma.depositRecord.findMany({
      where: { 
        userId,
        status: 'CONFIRMED'
      },
      select: {
        id: true,
        amount: true,
        status: true,
        createdAt: true,
        processedAt: true
      },
      orderBy: { createdAt: 'desc' },
      skip: (Number(page) - 1) * Number(limit),
      take: Number(limit)
    });

    const withdraws = await prisma.withdrawRecord.findMany({
      where: { 
        userId,
        status: 'CONFIRMED'
      },
      select: {
        id: true,
        amount: true,
        status: true,
        createdAt: true,
        processedAt: true
      },
      orderBy: { createdAt: 'desc' },
      skip: (Number(page) - 1) * Number(limit),
      take: Number(limit)
    });

    // 合并并按时间排序
    const transactions = [
      ...deposits.map(d => ({
        id: `deposit_${d.id}`,
        type: 'DEPOSIT',
        amount: d.amount,
        status: d.status,
        createdAt: d.createdAt,
        processedAt: d.processedAt
      })),
      ...withdraws.map(w => ({
        id: `withdraw_${w.id}`,
        type: 'WITHDRAW',
        amount: w.amount,
        status: w.status,
        createdAt: w.createdAt,
        processedAt: w.processedAt
      }))
    ].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

    res.json(ApiResponse.success({
      transactions: transactions.slice(0, Number(limit)),
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total: transactions.length
      }
    }));
  } catch (error) {
    console.error('잔액 내역 조회 오류:', error);
    res.status(500).json(ApiResponse.error('잔액 내역 조회에 실패했습니다.'));
  }
});

export default router;